package com.taiyuan.zfmvp.JUC.three;

import java.util.Random;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

/**
 * @param
 * @Author: zhoufang@si-tech.com.cn
 * @Descriiption:
 * @Date 2022/10/6
 * @return
 */
public class SemaphoreDemo {

    //六辆汽车停三个停车位

    public static void main(String[] args) {

        //创建semaphore
        Semaphore semaphore = new Semaphore(3);

        //模拟6辆汽车
        for (int i = 0; i < 6; i++) {
            new Thread(new Runnable() {
                @Override
                public void run() {

                    try {
                        //抢占车位
                        semaphore.acquire();
                        System.out.println(Thread.currentThread().getName()+ " 抢到了车位");

                        //设置随机停车时间
                        TimeUnit.SECONDS.sleep(new Random().nextInt(5));

                        System.out.println(Thread.currentThread().getName()+ " ---------离开了车位");
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }finally {
                        //释放
                        semaphore.release();
                    }

                }
            },String.valueOf(i)).start();
        }

    }

}
